package com.totobox.apps.activity;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.totobox.apps.Const;
import com.totobox.apps.R;
import com.totobox.apps.common.CustomMediaController;
import com.totobox.apps.common.ImageDownloader;
import com.totobox.apps.common.Util;

public class TotoMusicPlayerActivity extends BasicActivity {

	private static final int NOTIFY_ME_ID = 1337;
	private int count = 0;

	private CustomMediaController control;
	private MediaPlayer mPlayer;

	public MediaStore mStore;

	public ImageView album_img;
	
	public TextView m_title;
	public TextView m_artist;

	public ProgressBar play_progress;

	public TextView txt_start_time;
	public TextView txt_end_time;

	public ImageButton btn_m_rewind;
	public ImageButton btn_start;
	public ImageButton btn_m_forword;

	public SeekBar volumn_seek;

	public AudioManager audioManager;

	public int maxVolumn;
	public int currentVolumn;

	public ListView musicList;
	public MusicListAdapter listAdapter;

	// 데이터
	private ProgressDialog progressDialog;
	final public int PROGRESS_DIALOG = 0;

	public Handler handler = new Handler();

	private int position = 0;
	private int total_position = 0;
	private Map<String, String> mData;
	private String mp3_url = "";

	public boolean wasPlaying;
	
	private FileInputStream fis;

	private final ImageDownloader imageDownloader = new ImageDownloader();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.toto_music_view);

		// 상단 타이틀 초기화
		super.initTitle();

		// 하단 메뉴 세팅
		super.setFooterMenu(this);

		album_img =  (ImageView) findViewById(R.id.album_img);
		m_title = (TextView) findViewById(R.id.m_title);
		m_artist = (TextView) findViewById(R.id.m_artist);

		txt_start_time = (TextView) findViewById(R.id.txt_start_time);
		txt_end_time = (TextView) findViewById(R.id.txt_end_time);

		play_progress = (ProgressBar) findViewById(R.id.play_progress);

		btn_m_rewind = (ImageButton) findViewById(R.id.btn_m_rewind);
		btn_start = (ImageButton) findViewById(R.id.btn_start);
		btn_m_forword = (ImageButton) findViewById(R.id.btn_m_forword);
		
		//이벤트 등록
		btn_m_rewind.setOnClickListener(this);
		btn_start.setOnClickListener(this);
		btn_m_forword.setOnClickListener(this);
		
		if (Const.dnQueue != null && !Const.dnQueue.isEmpty()) {
			total_position = Const.dnQueue.size();
			//mData = Const.dnQueue.get(position);
		}
		
		// 플레이어
		mPlayer = new MediaPlayer();
		mPlayer.setOnCompletionListener(mOnComplete);
		mProgressHandler.sendEmptyMessageDelayed(0,500);
		
		//소리 조절
		this.setVolumnBar();
		
		// 첫 곡 읽기 및 준비
        if (LoadMedia(position) == false) {
            Toast.makeText(this, "파일을 읽을 수 없습니다.", Toast.LENGTH_LONG).show();
        }
        
        //앨범 이미지
        imageDownloader.download(mData.get("vcThumbNailInfo"), album_img);
        
        //music list
        handler.post(musicAdapter);
    	
	}

	@Override
	public void onClick(View v) {

		//mStore = new MediaStore();
		//이전
		if(btn_title_left == v){
			finish();
		}
		else if(btn_start == v){
			if (mPlayer.isPlaying() == false) {
				btn_start.setImageDrawable(getResources().getDrawable(R.drawable.icon_m_pause));
                mPlayer.start();
           } else {
        	   btn_start.setImageDrawable(getResources().getDrawable(R.drawable.icon_m_start));
        	   mPlayer.pause();
           }
		}
		else if(btn_m_rewind == v){
			
			boolean wasPlaying = mPlayer.isPlaying();
			position = (position == 0 ? Const.dnQueue.size() - 1:position - 1);
            mPlayer.reset();
            LoadMedia(position);
            // 이전에 재생중이었으면 다음 곡 바로 재생
            if (wasPlaying) {
            	mPlayer.start();
            	btn_start.setImageDrawable(getResources().getDrawable(R.drawable.icon_m_pause));
            }
		}
		else if(btn_m_forword == v){
			
			boolean wasPlaying = mPlayer.isPlaying();
            position = (position == Const.dnQueue.size() - 1 ? 0:position + 1);
            mPlayer.reset();
            LoadMedia(position);
            // 이전에 재생중이었으면 다음 곡 바로 재생
            if (wasPlaying) {
                 mPlayer.start();
                 btn_start.setImageDrawable(getResources().getDrawable(R.drawable.icon_m_pause));
            }
		}
	}

	/**
	 * json 데이터
	 */
	private Runnable musicAdapter = new Runnable() {
		public void run() {
			try {
				if (Const.dnQueue != null && !Const.dnQueue.isEmpty()) {

					listAdapter = new MusicListAdapter(TotoMusicPlayerActivity.this,R.layout.item_music_list, Const.dnQueue);
					musicList.setAdapter(listAdapter);
					
				} else {
					showNotFoundData();
				}

				//progressDialog.dismiss();
				//TotoMusicPlayerActivity.this.removeDialog(PROGRESS_DIALOG);

			} catch (Exception e) {
				Log.e("xml-data", e.toString());
			}
		}
	};

	private void showNotFoundData() {
		Toast toast = Toast.makeText(this, "음악 파일이 없습니다.", Toast.LENGTH_SHORT);
		toast.show();
	}

	class MusicListAdapter extends ArrayAdapter {
		int courser = 0;
		private int layout;
		private Activity context;
		List<Map<String, String>> list;

		@SuppressWarnings("unchecked")
		public MusicListAdapter(Activity context, int layout,List<Map<String, String>> list) {
			super(context, layout, list);
			this.context = context;
			this.list = list;
			this.layout = layout;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			Map<String, String> map = list.get(position);
			
			LayoutInflater inflater = context.getLayoutInflater();
			View view = inflater.inflate(layout, null);
			TextView txt_list_name = (TextView) view.findViewById(R.id.txt_list_name);
			txt_list_name.setText(map.get("vcName"));
			
			ImageView btn_bookmark = (ImageView) view.findViewById(R.id.btn_bookmark);
			
			//북마크 버튼에 position 을 세팅
			btn_bookmark.setId(courser);
			btn_bookmark.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//북마크 버튼의 id 값을 가져 온다.
					clickedBookmark(v.getId());
				}
			});
			
			courser++;
			
			return view;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> adapter, View v, int position,long id) {
		
	}

	/**
	 * 북마크 클릭
	 */ 
	public void clickedBookmark(int position){
		
		super.showText(this, "즐겨찾기에 추가되었습니다.");
		
		Map<String,String> jsonData = Const.dnQueue.get(position);
	}
	
	/**
	 * 음악 플레이시 노티파이에 등록 한다.
	 * @param title
	 * @param msg
	 */
	private void notifyMe(String title, String msg) {

		final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		Notification note = new Notification(R.drawable.icon_arrow, title , System.currentTimeMillis());
		PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this,TotoMusicPlayerActivity.class), 0);
		note.setLatestEventInfo(this, title, msg, i);
		note.number = ++count;
		mgr.notify(NOTIFY_ME_ID, note);
	}

	// 항상 준비 상태여야 한다.
	boolean LoadMedia(int idx) {
		try {
			
			mData = Const.dnQueue.get(position);
			
			//mp3 경로임.
			String title = mData.get("vcName");
			mp3_url = mData.get("vcOriginStream");

			mp3_url = "rtsp://1.234.52.123/vod/_definst/mp4:sample01_256k.m4a";
			
			mPlayer.setDataSource(mp3_url);
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
			//mPlayer.prepareAsync();
			
			this.Prepare();
			
			//플레이 시작
			mPlayer.start();
			
			//앨범 제목
			m_title.setText(title);
			
			int max = Util.stringToInt(mData.get("vcFilePlayTime"),0);
			
			//진행바 
			play_progress.setMax(max);
			
			//플레이 시간
			txt_end_time.setText(Util.getStrTime(max));
			
			this.notifyMe(title , "Toto Fun Music");
			
		} catch (IllegalArgumentException e) {
			return false;
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		if (Prepare() == false) {
			return false;
		}

		return true;
	}

	//진행 준비
	boolean Prepare() {
		try {
			mPlayer.prepare();
		} catch (IllegalStateException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		return true;
	}

	public void setVolumnBar() {

		/* 미디어 볼륨 조절 하는바 */
		volumn_seek = (SeekBar) findViewById(R.id.volumn_seek);
		audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		maxVolumn = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		currentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

		volumn_seek.setMax(maxVolumn);
		volumn_seek.setProgress(currentVolumn);

		volumn_seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
				audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress, 0);
			}
		});
	}
	
	// 재생 완료되면 다음곡으로
    MediaPlayer.OnCompletionListener mOnComplete = new MediaPlayer.OnCompletionListener() {
          public void onCompletion(MediaPlayer arg0) {
        	  
        	  position = (position == Const.dnQueue.size() - 1 ? 0:position + 1);
        	  if(position < total_position){
        		  mPlayer.reset();
        		  LoadMedia(position);
        		  mPlayer.start();
        	  }
          }
    };
 
    // 에러 발생시 메시지 출력
    MediaPlayer.OnErrorListener mOnError = new MediaPlayer.OnErrorListener() {
          public boolean onError(MediaPlayer mp, int what, int extra) {
              String err = "OnError occured. what = " + what + " ,extra = " + extra;
              Toast.makeText(TotoMusicPlayerActivity.this, err, Toast.LENGTH_LONG).show();
              return false;
          }
    };
   
    //0.2초에 한번꼴로 재생 위치 갱신
     Handler mProgressHandler = new Handler() {
          public void handleMessage(Message msg) {
              if (mPlayer == null) return;
              if (mPlayer.isPlaying()) {
            	  play_progress.setProgress(mPlayer.getCurrentPosition());
            	  txt_start_time.setText(Util.getStrTime(mPlayer.getCurrentPosition()));
              }
              mProgressHandler.sendEmptyMessageDelayed(0,500);
          }
     };
    
}